// packageA/pages/repairLogisticsAdd/repairLogisticsAdd.js
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {areaList} from '@vant/area-data';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //是否是修改
    isEdit:false,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //配件列表
    partList:[],
    //当前配件
    currentPart:null,
    //当前配件
    currentIndex:0,
    //物流信息
    logisticsInfo:null,
    //省市区
    showArea: false,
    //省市区组件的数据
    areaList 
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('添加物流传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.repairId){
        //获取修改数据
        this.getInfo();
      }

      //是否是编辑
      if(paramObj.logisticsId){
        this.setData({
          isEdit: true
        })
      }else if(paramObj.repairId){
        //添加时获取维修工单信息
        this.getOrderInfo();
      }   
    }
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let logisticsInfo=td.logisticsInfo;
    let editInfo=td.editInfo;
    let partList=td.partList;
    let arr=[];

    //非空验证
      //收货人
      let name=obj.name.trim();
      if(!this.formNotEmpty(name,'nameMessage','请输入收货人')){
        return;
      }

      //手机号
      let phone=obj.phone.trim();
      if(!this.formNotEmpty(phone,'phoneMessage','请输入手机号')){
        return;
      }
      //手机号格式
      if(!util.checkPhoneFormat(phone)){
        this.setData({
          phoneMessage: '手机号格式错误',
          disabled:true
        })
        return;
      }

      //物流公司
      if(!editInfo.logCompany){
        Toast.fail('请选择物流公司');
        return;
      }

      //物流单号
      let odd=obj.odd.trim();
      if(!this.formNotEmpty(odd,'oddMessage','请输入物流单号')){
        return;
      }

      //地区必填
      if(!editInfo.addressArea){
        Toast.fail('请选择地区');
        return;
      }

      //收货地址
      let shippingAddress=obj.shippingAddress.trim();
      if(!this.formNotEmpty(shippingAddress,'shippingAddressMessage','请输入收货地址')){
        return;
      }

    //运费为数字
    let freight=obj.freight.trim();
    if(freight!='' && freight!=null){
      if(!(/^\d+(\.\d+)?$/.test(freight))){
        this.setData({
          freightMessage: '运费为数字',
          disabled: true
        });
        return;
      }
    }

    //处理配件
    let partListNew=[];
    if(partList.length){
      let len=partList.length-1;
      if(partList[len].partName && partList[len].factory && partList[len].factory.id){
      }else{
        Toast.fail('当前配件信息未完成');
        return;
      }

      partList.forEach(item => {
        partListNew.push({
          part: {
            code: item.partCode,
            name: item.partName,
            specParam: item.specParam
          },
          factory: {
            id: item.factory.id,
            name: item.factory.name,
            factoryDepart: item.factory.factoryDepart,
            UFIDACode: item.factory.UFIDACode ? item.factory.UFIDACode : null
          },
          salePrice: Number(item.salePrice),
          num: item.num,
          remark: item.remark
        });
      });
    }else{
      Toast.fail('请添加配件');
      return;
    }

    let loObj={
      self: false, //暂时无用
      consignee: {
        name: name,
        phone: phone,
      },
      logCompany: editInfo.logCompany,
      odd: odd,
      //省市区
      addressArea: editInfo.addressArea,
      //地址
      shippingAddress: shippingAddress,
      freight: Number(freight),
      returned: editInfo.returned ? editInfo.returned : false,
      remark: obj.remark.trim(),      
      parts: partListNew
    }

    if(logisticsInfo && logisticsInfo.logistics && logisticsInfo.logistics.length){
      if(td.isEdit){
        //编辑
        loObj.id=editInfo.id;
        logisticsInfo.logistics.forEach(item => {
          if(item.id!=editInfo.id){
            arr.push(item);
          }
        });
      }else{
        //添加
        loObj.id=new Date().getTime();
        arr=logisticsInfo.logistics;
      }
    }else{
      loObj.id=new Date().getTime();
    }

    arr.push(loObj);

    let param={
      className:'afterSaleMaintainOrder',
      data:{        
        id: this.data.paramObj.repairId,
        logistics: arr
      }
    }

    // console.log(param.data);
    // return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');
        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleMaintainOrder',
      data: {
        id: this.data.paramObj.repairId,
        selectFields: ['id','logistics']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        if(result.logistics && result.logistics.length){
          console.log('物流列表');
          console.log(result.logistics);          
  
          this.setData({
            logisticsInfo: result
          })

          //编辑
          if(this.data.isEdit){
            result.logistics.forEach(item => {
              if(item.id==this.data.paramObj.logisticsId){
                //旧件退回
                item.returned+='';

                //省市区
                if(item.addressArea && item.addressArea.length){
                  let names=[];
                  item.addressArea.forEach(item=>{
                    names.push(item.name);
                  });
                  item.self_area=names;
                }

                this.setData({
                  editInfo: item
                })

                //配件
                if(item.parts && item.parts.length){
                  item.parts.forEach(item2 => {
                    item2.partCode = item2.part.code;
                    item2.partName = item2.part.name;
                    item2.specParam = item2.part.specParam;
                  });

                  this.setData({
                    partList: item.parts
                  })
                }
              }
            });

            console.log('物流信息回显');
            console.log(this.data.editInfo);
          }
        }  
      }
    }).catch((error) => {
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //物流公司
    if(field=='logCompany'){
      this.setData({
        selectTitle: '物流公司',
        showSelectSearch: false
      })
      this.getLogCompanyList();
    }

    //配件厂家
    if(field=='factory'){
      this.setData({
        selectTitle: '配件厂家',
        showSelectSearch: true,
        currentIndex: dataset.index,
        currentPart: dataset.current
      })
      this.getFactoryList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //物流公司
    if(selectField=='logCompany'){
      obj='editInfo.logCompany';
    }

    //配件厂家
    if(selectField=='factory'){
      let obj=e.detail.value.obj;
      let currentIndex=this.data.currentIndex; 
      let partList=this.data.partList;

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          item.factory=obj;
        }
      });

      this.setData({
        partList:partList,
        disabled: false
      })
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //配件厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }
  },

  //查询物流公司
  getLogCompanyList(){
    let param = {
      isAuth: false,
      className: 'logisticsCompany',
      data: {
        searchAll: true,       
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //扫码
  onScanCode(e) {
    var _this = this;
    wx.scanCode({
      success: (res) => {
        let odd='editInfo.odd';
        _this.setData({
          [odd]: res.result
        })
      }
    })
  },

  //旧件退回
  onChangeReturned(event) {
    let returned='editInfo.returned';
    this.setData({
      [returned]: event.detail,
    })
  },

  //添加配件
  onAddPart(){
    let list=this.data.partList;
    
    if(list.length){
      let len=list.length-1;
      //未填写不能加新的
      if(list[len].partName && list[len].factory && list[len].factory.id){
      }else{
        Toast.fail('当前配件信息未完成');
        return;
      }
    }

    list.push({
      part: null,
      partCode: null,
      partName: null,
      specParam: null,
      factory: null,
			salePrice: 0,
			num: 1,
			remark: null
    });

    this.setData({ 
      partList: list,
      disabled: false
    })
  },

  //获取配件输入的值
  onGetValue(e){
    let dataset=e.currentTarget.dataset;
    let val=e.detail;
    let partList=this.data.partList;
   
    partList.forEach((item,index) => {
      if(index==dataset.index){
        item[dataset.field]=val.trim();
      }
    }); 

    this.setData({ 
      partList: partList,
      disabled: false
		})
  },

  //删除配件
  ondeletePart(e){
    Dialog.confirm({
      title: '确认删除此配件吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list=this.data.partList;
      let dataset=e.currentTarget.dataset;
      let arr=[];
      
      list.forEach((item,index) => {
        if(index!=dataset.index){
          arr.push(item);
        }
      });
  
      this.setData({ 
        partList: arr 
      }) 
    }).catch(() => {
    });  
  },

  //查询配件厂家
  getFactoryList(){
    let param = {
      isAuth: true,
      className: 'supplierFactories',
      data: {
        searchAll: true,
        selectFields: ['id','name','factoryDepart','UFIDACode']
      }
    }
   
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取配件数量
  onChangeNum(e) {
    let list=this.data.partList;
    let dataset=e.currentTarget.dataset;
    
    list.forEach((item,index) => {
      if(index==dataset.index){
        item.num=e.detail;
      }
    });

    this.setData({ 
      partList: list,
      disabled: false 
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },

  //获取维修工单信息
  getOrderInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleMaintainOrder',
      data: {
        id:this.data.paramObj.repairId,
        selectFields: ['id','repairInfo']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result[0];
        console.log('维修工单信息');
        console.log(result);

        //显示收货人电话地址
        let consignee='editInfo.consignee';
        let addressArea='editInfo.addressArea';
        let self_area='editInfo.self_area';
        let shippingAddress='editInfo.shippingAddress'; 
        let names=[];
       
        if(result.repairInfo.addressArea && result.repairInfo.addressArea.length){ 
          result.repairInfo.addressArea.forEach(item=>{
            names.push(item.name);
          });
        }

        this.setData({
          [consignee]: {
            name: result.repairInfo.name,
            phone: result.repairInfo.phone
          },
          [addressArea]: result.repairInfo.addressArea ? result.repairInfo.addressArea : null,
          [self_area]: names,
          [shippingAddress]: result.repairInfo.address
        })     
      }
    }).catch((error) => {
    })
  },

  //显示省市区
  onShowArea(){
    this.setData({
			showArea: true
    })
  },

  //隐藏省市区
  onCloseArea(){
    this.setData({
			showArea: false
    })
  },

  //确认省市区
  onConfirmArea({detail}){
    let arr=detail.values;   
    let names=[];
    arr.forEach(item=>{
      names.push(item.name);
    });

    let addressArea='editInfo.addressArea';
    let self_area='editInfo.self_area';
    this.setData({
      [addressArea]: arr,
      [self_area]: names,
      disabled: false
    })

    this.onCloseArea();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})